package net.xxcl.kygl.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Cell;
import net.xxcl.kygl.mapper.FruitMapper;
import net.xxcl.kygl.mapper.FruittypeMapper;
import net.xxcl.kygl.mapper.UserMapper;
import net.xxcl.kygl.pojo.Criteria;
import net.xxcl.kygl.pojo.Fruit;
import net.xxcl.kygl.pojo.Fruittype;
import net.xxcl.kygl.pojo.User;
import net.xxcl.kygl.util.CheckStr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional()
public class FruitService {
    @Autowired
    private FruitMapper fruitMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FruittypeMapper fruittypeMapper;

    private static final Logger logger = LoggerFactory.getLogger(FruitService.class);

    public int countByExample(Criteria example) {
        int count = this.fruitMapper.countByExample(example);
        logger.debug("count: {}", count);
        return count;
    }

    public Fruit selectByPrimaryKey(Integer id) {
        return this.fruitMapper.selectByPrimaryKey(id);
    }

    public List<Fruit> selectByExample(Criteria example) {
        return this.fruitMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(Integer id) {
        return this.fruitMapper.deleteByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(Fruit record) {
        return this.fruitMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(Fruit record) {
        return this.fruitMapper.updateByPrimaryKey(record);
    }

    public int deleteByExample(Criteria example) {
        return this.fruitMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(Fruit record, Criteria example) {
        return this.fruitMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(Fruit record, Criteria example) {
        return this.fruitMapper.updateByExample(record, example);
    }

    public int insert(Fruit record) {
        return this.fruitMapper.insert(record);
    }

    public int insertSelective(Fruit record) {
        return this.fruitMapper.insertSelective(record);
    }

    /**
     * 导入excel的一行记录
     * @param cells
     * @return
     */
    public Boolean saveExcelRow(Cell[] cells){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
            String username = cells[1].getContents().trim();
            String name = cells[2].getContents().trim();
            String dept = cells[3].getContents().trim();
            String time = cells[4].getContents().trim().replaceAll("．",".");
            String journal = cells[5].getContents().trim();
            String fruitTypeName = cells[6].getContents().trim();
            String rankAndCount = cells[7].getContents().trim();System.out.println(cells.length);
            String note = "";
            if(cells.length>8){
                note = cells[8].getContents().trim();
            }

            if(username.equalsIgnoreCase("") || name.equalsIgnoreCase("") || dept.equalsIgnoreCase("")){
                throw new RuntimeException("作者姓名，成果名称，成果来源不能为空");
            }

            Criteria criteria = new Criteria();
            Fruit fruit = new Fruit();
            List<User> users = new ArrayList<User>();
            if(CheckStr.isNumeric(username)){
                //用工号查找
                criteria.put("name",username);
                users = userMapper.selectByExample(criteria);
            } else {
                //用姓名查找，可能会有重名
                criteria.put("username",username);
                users = userMapper.selectByExample(criteria);
            }
            if(users.size()==1){
                fruit.setUserid(users.get(0).getId());
            } else if(users.size()>1) {
                throw new RuntimeException("姓名"+username+"有重名，请用工号代替");
            } else {
                throw new RuntimeException(username+"不存在");
            }
            criteria.clear();
            criteria.put("userid",fruit.getUserid());
            criteria.put("name",name);
            criteria.put("dept",dept);
            List<Fruit> fruits = fruitMapper.selectByExample(criteria);
            if(fruits.size()>0){
                throw new RuntimeException("作者姓名、成果名称、来源均已存在，请检查是否重复导入");
            }
            fruit.setName(name);
            fruit.setDept(dept);
            Date date = null;
            try{
                date = sdf.parse(time);
            } catch (ParseException e) {
                throw new RuntimeException("成果取得时间格式不对");
            }
            fruit.setTime(date);
            if(!journal.equals("")){
                fruit.setJournal(journal);
            }
            criteria.clear();
            criteria.put("name",fruitTypeName);
            List<Fruittype> fruittypes = fruittypeMapper.selectByExample(criteria);
            if(fruittypes.size()>0){
                fruit.setFruittype(fruittypes.get(0).getId());
            } else {
                throw new RuntimeException("成果类型"+fruitTypeName+"不存在，请先添加");
            }
            if(rankAndCount.equals("独撰")){
                fruit.setRank(1);
                fruit.setCount(1);
            } else {
                String[] temp = rankAndCount.split("/");
                if(temp.length<=1){
                    throw new RuntimeException("合作排名情况格式不对");
                } else {
                    fruit.setRank(Integer.parseInt(temp[0]));
                    fruit.setCount(Integer.parseInt(temp[1]));
                }
            }
            if(!note.equals("")){
                fruit.setNote(note);
            }
            fruit.setState(1);
            fruitMapper.insertSelective(fruit);
            return true;
        } catch (RuntimeException e){
            throw e;
        }
    }
}